import os
import ckeynsecret

from django.utils import simplejson

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template

from myspace.myspaceapi import MySpace, MySpaceError
from oauthlib import oauth
from entities import WinLoss

class Invite(webapp.RequestHandler):
  def get(self):
    id = self.request.get('opensocial_viewer_id')
    appid = self.request.get('appid')
    opensocial_token = self.request.get('opensocial_token')

    error = False
    
    try:
        int(id)
        int(appid)
    except:
        error = True
    
    ms = MySpace(ckeynsecret.CONSUMER_KEY, ckeynsecret.CONSUMER_SECRET)
    ms.token = oauth.OAuthToken('', '')
    
    try:
        friends = ms.get_friends(id)
    except MySpaceError, mse:
        error = True

    if error:
        msg = 'Oops, there was an error, try refreshing the page!'
        self.response.out.write(msg)
        return
    
    json = simplejson.dumps(friends)
    if json is None:
        json = '{}'
    
    template_values = {
      'friends_obj': json,
      'appid': appid,
      'ownerId': id,
      'opensocial_token': opensocial_token
    }
    
    path = os.path.join(os.path.dirname(__file__), 'invite.html')
    self.response.out.write(template.render(path, template_values))

application = webapp.WSGIApplication(
                                     [('/invite', Invite)],
                                     debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()